document.addEventListener('DOMContentLoaded', function() {
    console.log('OTA Server 页面已加载');
    
    // DOM 元素
    const loginPage = document.getElementById('login-page');
    const mainPage = document.getElementById('main-page');
    const productsPage = document.getElementById('products-page');
    const productDetailPage = document.getElementById('product-detail-page');
    const firmwarePage = document.getElementById('firmware-page');
    
    // 登录功能
    const loginBtn = document.getElementById('login-btn');
    const username = document.getElementById('username');
    const password = document.getElementById('password');
    const logoutBtn = document.getElementById('logout-btn');
    
    loginBtn.addEventListener('click', function() {
        // 简单的登录验证，实际应用中应使用更安全的方式
        if (username.value && password.value) {
            loginPage.classList.add('d-none');
            mainPage.classList.remove('d-none');
            // 可以在此处加载产品数据
            loadProducts();
        } else {
            alert('请输入用户名和密码');
        }
    });
    
    logoutBtn.addEventListener('click', function() {
        mainPage.classList.add('d-none');
        loginPage.classList.remove('d-none');
        // 清空输入框
        username.value = '';
        password.value = '';
    });
    
    // 页面导航链接
    const productsLink = document.getElementById('products-link');
    productsLink.addEventListener('click', function() {
        showPage(productsPage);
    });
    
    // 返回按钮事件
    const backToProductsBtn = document.getElementById('back-to-products');
    backToProductsBtn.addEventListener('click', function() {
        productDetailPage.classList.add('d-none');
        productsPage.classList.remove('d-none');
    });
    
    const backToProductDetailBtn = document.getElementById('back-to-product-detail');
    backToProductDetailBtn.addEventListener('click', function() {
        firmwarePage.classList.add('d-none');
        productDetailPage.classList.remove('d-none');
    });
    
    // 添加产品模态框
    const addProductBtn = document.getElementById('add-product-btn');
    const addProductModal = new bootstrap.Modal(document.getElementById('add-product-modal'));
    
    addProductBtn.addEventListener('click', function() {
        addProductModal.show();
    });
    
    // 添加型号模态框
    const addModelBtn = document.getElementById('add-model-btn');
    const addModelModal = new bootstrap.Modal(document.getElementById('add-model-modal'));
    
    addModelBtn.addEventListener('click', function() {
        addModelModal.show();
    });
    
    // 添加固件模态框
    const addFirmwareBtn = document.getElementById('add-firmware-btn');
    const addFirmwareModal = new bootstrap.Modal(document.getElementById('add-firmware-modal'));
    
    addFirmwareBtn.addEventListener('click', function() {
        addFirmwareModal.show();
    });
    
    // 图片预览功能
    setupImagePreview('front-image', 'front-image-preview');
    setupImagePreview('left-image', 'left-image-preview');
    setupImagePreview('top-image', 'top-image-preview');
    setupImagePreview('model-image', 'model-image-preview');
    
    // MD5计算功能
    document.getElementById('firmware-file').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            calculateMD5(file);
        }
    });
    
    // 右键菜单
    const contextMenu = document.getElementById('context-menu');
    document.addEventListener('contextmenu', function(e) {
        // 检查是否在产品卡片上右键
        let targetElement = e.target;
        while (targetElement != null) {
            if (targetElement.classList && targetElement.classList.contains('product-card')) {
                e.preventDefault();
                contextMenu.style.display = 'block';
                contextMenu.style.left = e.pageX + 'px';
                contextMenu.style.top = e.pageY + 'px';
                
                // 存储当前卡片的ID或其他数据，以便于处理
                contextMenu.dataset.targetId = targetElement.dataset.id || '';
                return;
            }
            targetElement = targetElement.parentElement;
        }
    });
    
    // 点击其他地方隐藏右键菜单
    document.addEventListener('click', function() {
        contextMenu.style.display = 'none';
    });
    
    // 右键菜单项点击事件
    document.getElementById('add-firmware-context').addEventListener('click', function() {
        const id = contextMenu.dataset.targetId;
        console.log('为产品ID：' + id + ' 添加固件');
        // 这里可以跳转到固件页面或打开添加固件模态框
        addFirmwareModal.show();
    });
    
    document.getElementById('edit-product-context').addEventListener('click', function() {
        const id = contextMenu.dataset.targetId;
        console.log('编辑产品ID：' + id);
        // 打开编辑产品模态框
    });
    
    document.getElementById('delete-product-context').addEventListener('click', function() {
        const id = contextMenu.dataset.targetId;
        if (confirm('确定要删除此产品吗？')) {
            console.log('删除产品ID：' + id);
            // 删除产品的代码
        }
    });
    
    // 辅助函数
    function showPage(page) {
        // 隐藏所有页面
        const pages = [productsPage, productDetailPage, firmwarePage];
        pages.forEach(p => p.classList.add('d-none'));
        
        // 显示目标页面
        page.classList.remove('d-none');
    }
    
    function setupImagePreview(inputId, previewId) {
        const input = document.getElementById(inputId);
        const preview = document.getElementById(previewId);
        
        if (input && preview) {
            input.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        preview.style.backgroundImage = `url(${event.target.result})`;
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
    }
    
    function calculateMD5(file) {
        const reader = new FileReader();
        reader.readAsBinaryString(file);
        
        reader.onload = function() {
            const md5 = SparkMD5.hashBinary(reader.result);
            document.getElementById('md5-value').textContent = 'MD5: ' + md5;
        };
        
        reader.onerror = function() {
            console.error('计算MD5失败');
            document.getElementById('md5-value').textContent = 'MD5计算失败';
        };
    }
    
    // 模拟数据加载
    function loadProducts() {
        const productList = document.getElementById('product-list');
        
        // 模拟产品数据
        const products = [
            { id: 1, name: '智能手表系列', description: '高端智能穿戴设备', images: ['placeholder.jpg', 'placeholder.jpg', 'placeholder.jpg'] },
            { id: 2, name: '健康监测仪系列', description: '专业健康数据监测设备', images: ['placeholder.jpg', 'placeholder.jpg', 'placeholder.jpg'] }
        ];
        
        productList.innerHTML = '';
        products.forEach(product => {
            const productCard = `
                <div class="col">
                    <div class="product-card" data-id="${product.id}">
                        <div class="product-image" style="background-image: url('placeholder.jpg')">
                            <div class="product-image-nav">
                                <button class="view-front"><i class="fas fa-th-large"></i></button>
                                <button class="view-left"><i class="fas fa-th-large"></i></button>
                                <button class="view-top"><i class="fas fa-th-large"></i></button>
                            </div>
                        </div>
                        <div class="product-body">
                            <h5>${product.name}</h5>
                            <p>${product.description}</p>
                        </div>
                    </div>
                </div>
            `;
            productList.innerHTML += productCard;
        });
        
        // 添加产品卡片点击事件，跳转到产品详情页
        const productCards = document.querySelectorAll('.product-card');
        productCards.forEach(card => {
            card.addEventListener('click', function() {
                const productId = this.dataset.id;
                console.log('查看产品详情：' + productId);
                
                // 加载并显示产品详情
                showProductDetail(productId);
            });
        });
    }
    
    function showProductDetail(productId) {
        // 模拟加载产品详情
        document.getElementById('product-series-name').textContent = `产品系列 #${productId}`;
        document.getElementById('product-description').textContent = '这是产品系列的详细描述...';
        
        // 模拟加载产品型号
        const modelList = document.getElementById('model-list');
        modelList.innerHTML = '';
        
        // 模拟产品型号数据
        const models = [
            { id: 101, name: 'Model A', info: '入门级产品型号', releaseDate: '2023-01-15' },
            { id: 102, name: 'Model B', info: '高端产品型号', releaseDate: '2023-03-20' }
        ];
        
        models.forEach(model => {
            const modelCard = `
                <div class="col">
                    <div class="product-card" data-id="${model.id}">
                        <div class="product-image" style="background-image: url('placeholder.jpg')"></div>
                        <div class="product-body">
                            <h5>${model.name}</h5>
                            <p>${model.info}</p>
                            <small>发布日期: ${model.releaseDate}</small>
                        </div>
                    </div>
                </div>
            `;
            modelList.innerHTML += modelCard;
        });
        
        // 添加型号卡片点击事件，跳转到固件管理页
        const modelCards = document.querySelectorAll('#model-list .product-card');
        modelCards.forEach(card => {
            card.addEventListener('click', function() {
                const modelId = this.dataset.id;
                console.log('查看型号固件：' + modelId);
                
                // 加载并显示固件管理页面
                showFirmwareManagement(modelId);
            });
        });
        
        // 显示产品详情页
        showPage(productDetailPage);
    }
    
    function showFirmwareManagement(modelId) {
        // 模拟加载型号信息和固件列表
        document.getElementById('model-name').textContent = `产品型号 #${modelId}`;
        
        // 模拟固件数据
        const firmwareList = document.getElementById('firmware-list');
        firmwareList.innerHTML = '';
        
        // 模拟固件数据
        const firmwares = [
            { id: 1001, name: '标准版固件', version: 'v1.0.1', hardwareName: 'HW-A', extensionName: 'STD', md5: 'ab12cd34ef56...', date: '2023-05-10' },
            { id: 1002, name: '国际版固件', version: 'v1.0.2', hardwareName: 'HW-A', extensionName: 'INT', md5: '12ab34cd56ef...', date: '2023-06-15' }
        ];
        
        firmwares.forEach(firmware => {
            const row = `
                <tr>
                    <td>${firmware.name}</td>
                    <td>${firmware.version}</td>
                    <td>${firmware.hardwareName}</td>
                    <td>${firmware.extensionName}</td>
                    <td>${firmware.md5}</td>
                    <td>${firmware.date}</td>
                    <td>
                        <button class="btn btn-sm btn-info">查看</button>
                        <button class="btn btn-sm btn-danger">删除</button>
                    </td>
                </tr>
            `;
            firmwareList.innerHTML += row;
        });
        
        // 显示固件管理页面
        showPage(firmwarePage);
    }
});
